
package com.yuan.graduate;

import com.yuan.application.ApplicationCleaner;
import com.yuan.application.BaseActivity;
import com.yuan.control.SettingControl;
import com.yuan.dialog.CustomProgressDialog;
import com.yuan.dialog.DialogUtil;
import com.yuan.model.Users;
import com.yuan.unit.AsyncDataJobHandler;
import com.yuan.unit.NetUtils;
import com.yuan.unit.ToastHelper;
import com.yuan.view.Commhead;

import org.json.JSONException;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.EditText;
import android.widget.ImageButton;

/**
 * 登陆界面
 * 
 * @author YUAN
 */
@SuppressLint("HandlerLeak")
public class LoginActivity extends BaseActivity implements OnClickListener, OnCheckedChangeListener {
    private EditText et_uname = null, et_pw = null;
    private Button btn_login = null;
    private ImageButton ib_host_setting = null;
    private CheckBox cb_auto_login = null, cb_remember_pw = null;
    private Context mContext = null;
    private long mExitTime = 0;
    private CustomProgressDialog mProgressDialog = null;
    private Commhead login_head = null;

    /**
     * 队返回来的数据进行相应的处理
     */
    private Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what)
            {
                case MSG_GETCONFIGSESSED:
                    try {
                        DialogUtil.createChangeComnfigDialog(mContext).show();
                    } catch (JSONException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                    break;
                case MSG_GETCONFIGFILED:
                    DialogUtil.createCommonDialog(mContext, "信息提示",
                            "获取配置文件失败，可能原因：1.服务器没开 2.网址配置错误")
                            .show();
                    break;
                case GETUSERINFOSESSED:
                    startActivity(new Intent(LoginActivity.this, MainActivity.class));
                    finish();
                    break;
                case GETUSERINFOFILED:
                    DialogUtil.createCommonDialog(mContext, "信息提示",
                            "登录失败，可能原因：1.服务器没开 2.账户密码错误 3.未设置电话号码")
                            .show();
                    break;
                case MSG_LOGINSFILED:
                    DialogUtil.createCommonDialog(mContext, "信息提示",
                            "登录失败，可能原因：1.服务器没开 2.账户密码错误 3.未设置电话号码")
                            .show();
                    break;
                default:
                    break;

            }
            if (mProgressDialog != null && mProgressDialog.isShowing())
            {
                mProgressDialog.dismiss();
                mProgressDialog = null;
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mContext = this;
        mActivityType = Activity_Splash;
        setContentView(R.layout.activity_login);
        initView();
    }

    private void initView() {
        // TODO Auto-generated method stub
        et_uname = (EditText) findViewById(R.id.et_uname);
        et_pw = (EditText) findViewById(R.id.re_change_et_pw);
        btn_login = (Button) findViewById(R.id.btn_login);
        ib_host_setting = (ImageButton) findViewById(R.id.ib_host_setting);
        cb_auto_login = (CheckBox) findViewById(R.id.cb_auto_login);
        cb_remember_pw = (CheckBox) findViewById(R.id.cb_remember_pw);
        login_head = (Commhead) findViewById(R.id.login_head);
        login_head.hintRightIcon();
        btn_login.setOnClickListener(this);
        ib_host_setting.setOnClickListener(this);
        cb_auto_login.setOnCheckedChangeListener(this);
        cb_remember_pw.setOnCheckedChangeListener(this);
        cb_auto_login.setChecked(SettingControl.isAutoLogin());
        cb_remember_pw.setChecked(SettingControl.isRememberPsd());
        getUserName();
        isAutoLogin();
    }

    private void isAutoLogin() {
        // TODO Auto-generated method stub
        try {
            boolean flag = getIntent().getExtras().getBoolean("isAutoLogin");
            if (flag) {
                mProgressDialog = new CustomProgressDialog(mContext);
                mProgressDialog.setUpdateMsg(R.string.is_logining);
                mProgressDialog.show();
                AsyncDataJobHandler.getInstance().Login(mHandler);
            }
        } catch (Exception e)
        {
            e.printStackTrace();
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub
        if (!NetUtils.isNetworkAvailable(mContext))
        {
            DialogUtil.createCommonDialog(mContext, "错误提示！", "网络不可用").show();
            return;
        }
        switch (v.getId())
        {
            case R.id.btn_login:
                String username = et_uname.getText().toString();
                String pwd = et_pw.getText().toString();
                if (TextUtils.isEmpty(pwd) || TextUtils.isEmpty(username))
                {
                    ToastHelper.getInstance().shortToast(mContext, "输入错误!");
                    return;
                }
                Users.getInstance().setUsername(username);
                Users.getInstance().setPwd(pwd);
                SaveUserNamePsd(username, pwd);
                AsyncDataJobHandler.getInstance().Login(mHandler);
                mProgressDialog = new CustomProgressDialog(mContext);
                mProgressDialog.setUpdateMsg(R.string.is_logining);
                mProgressDialog.show();
                break;
            case R.id.ib_host_setting:
                AsyncDataJobHandler.getInstance().getConfig(mHandler);
                mProgressDialog = new CustomProgressDialog(mContext);
                mProgressDialog.setUpdateMsg(R.string.init_confif);
                mProgressDialog.show();
                break;
            case R.id.back:
                ApplicationCleaner.getInstance().onApplicationDestroy();
                break;
            default:
                break;
        }
    }

    private void SaveUserNamePsd(String username, String psd) {
        // TODO Auto-generated method stub
        SettingControl.setUserName(username);
        if (cb_remember_pw.isChecked())
        {
            SettingControl.setPsd(psd);
        }
    }

    /**
     * 在配置文件中查看用于是否已经存贮卡了账目密码 如果已经存储则直接显示在输入框中
     */
    private void getUserName() {
        // TODO Auto-generated method stub
        String username = SettingControl.getUserName();
        String psd = SettingControl.getPsd();
        if (!TextUtils.isEmpty(username))
        {
            et_uname.setText(username);
            Users.getInstance().setUsername(username);
        }
        if (!TextUtils.isEmpty(psd))
        {
            et_pw.setText(psd);
            Users.getInstance().setPwd(psd);
        }
    }

    @Override
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        // TODO Auto-generated method stub
        switch (buttonView.getId())
        {
            case R.id.cb_auto_login:
                if (isChecked)
                {
                    cb_remember_pw.setChecked(true);
                    SettingControl.setRememberPsd(true);
                    cb_remember_pw.setClickable(false);
                } else
                {
                    cb_remember_pw.setClickable(true);
                }
                SettingControl.setAutoLogin(isChecked);
                break;
            case R.id.cb_remember_pw:
                SettingControl.setRememberPsd(isChecked);
                break;
            default:
                break;
        }
    }

    @Override
    public void onDestroy() {
        et_uname = null;
        et_pw = null;
        btn_login = null;
        ib_host_setting = null;
        cb_auto_login = null;
        cb_remember_pw = null;
        mContext = null;
        mHandler = null;
        mProgressDialog = null;
        super.onDestroy();
    }

    @Override
    public void onMyDestroy() {
        // TODO Auto-generated method stub
        et_uname = null;
        et_pw = null;
        btn_login = null;
        ib_host_setting = null;
        cb_auto_login = null;
        cb_remember_pw = null;
        mContext = null;
        mHandler = null;
        mProgressDialog = null;
        super.onMyDestroy();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK
                && event.getAction() == KeyEvent.ACTION_DOWN) {
            if ((System.currentTimeMillis() - mExitTime) > 2000) {
                mExitTime = System.currentTimeMillis();
                ToastHelper.getInstance().shortToast(this, "再按一次退出~");
            } else {
                ApplicationCleaner.getInstance().onApplicationDestroy();
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }
}
